# -*- coding:utf-8 -*-
import global_setting
import RedisHelper
import serialize
from conf import hosts
import json,time
import threading

class MonitorServer(object):
    def __init__(self):
        self.redis_conn= RedisHelper.RedisHelper()
        self.save_config_into_redis()
    
    def start(self):
        self.data_handle_run()
        self.recevice_client_data()
    
    #保存客户机配置信息到redis
    def save_config_into_redis(self):
        serialize.pull_cofig_redis(self, hosts.monitor_groups)
        
    #接收客户端传来的插件数据后存入redis
    def recevice_client_data(self):
        chan_sub  = self.redis_conn.subscribe()
        while True:
            #print chan_sub.parse_response()
            #host_service_data是一个列表，列表的第三项是插件运行数据
            host_service_data = chan_sub.parse_response()
            host_service_data = json.loads(host_service_data[2])
            host_service_data['time_stamp'] = time.time()
            service_data_key = "ServiceData::%s::%s"%(host_service_data['host_ip'],host_service_data['service'])
            self.redis_conn.set(service_data_key,json.dumps(host_service_data))
    
    def data_handle(self):
        #处理监控数据 
        serialize.data_process(self)
           
    def data_handle_run(self):
        #处理监控数据 ，独立线程
        t = threading.Thread(target=self.data_handle)
        t.start()
    
    def alert_handle(self):
        #处理报警信息 ，独立线程
        pass
            